﻿namespace LeetCodeProject._0001_1000._001_100._51_60._056;

public class Solution
{
    public int[][] Merge(int[][] intervals)
    {
        if (intervals == null)
            throw new ArgumentNullException();
        var input = intervals.Where(t => t != null && t.Length == 2).OrderBy(t => t[0]).ToList();
        var output = new List<int[]>(input.Count);
        if (input.Count == 0)
            return output.ToArray();
        var pre = input[0];
        for (int i = 1; i < input.Count; i++)
        {
            if (CanMerge(pre, input[i]))
            {
                pre = Merge(pre, input[i]);
            }
            else
            {
                output.Add(pre);
                pre = input[i];
            }
        }

        output.Add(pre);
        return output.ToArray();
    }

    private int[] Merge(int[] x, int[] y)
    {
        return new[] { Math.Min(x[0], y[0]), Math.Max(x[1], y[1]) };
    }

    private bool CanMerge(int[] x, int[] y)
    {
        return x[1] >= y[0] && y[1] >= x[0];
    }
}